package com.eapi.project.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eapi.eapicommom.model.entity.User;
import com.eapi.project.common.ErrorCode;
import com.eapi.project.exception.BusinessException;
import com.eapi.project.mapper.UserMapper;
import com.eapi.project.model.dto.mail.MailRequest;
import com.eapi.project.model.entity.Identifycode;
import com.eapi.project.service.IdentifycodeService;
import com.eapi.project.service.SendMailLoginService;
import com.eapi.project.service.SendMailService;
import com.eapi.project.service.UserService;
import com.eapi.project.utils.IdentifyingCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Service
public class SendMailLoginServiceImpl implements SendMailLoginService {
    @Resource
    private UserService userService;

    //注入邮件工具类
    @Autowired
    private JavaMailSender javaMailSender;

    @Resource
    private IdentifycodeService identifycodeService;

    @Resource
    private UserMapper userMapper;

    @Value("${spring.mail.username}")
    private String sendMailer;

    private static final Logger logger =  LoggerFactory.getLogger(SendMailLoginServiceImpl.class);

    public void checkMail(MailRequest mailRequest) {
        if(mailRequest==null || mailRequest.getSendTo()==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"邮箱格式异常");
        }
    }

    @Override
    public void sendSimpleMail(MailRequest mailRequest) {
        // 判断邮箱格式是否正确
        checkMail(mailRequest);
        // 判断邮箱是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("emailAddress",mailRequest.getSendTo());
        Long number = userMapper.selectCount(userQueryWrapper);
        if(number<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"邮箱未注册");
        }


        SimpleMailMessage message = new SimpleMailMessage();
        // checkMail(mailRequest);
        //邮件发件人
        message.setFrom(sendMailer);
        //邮件收件人 1或多个
        message.setTo(mailRequest.getSendTo());
        //邮件主题
        // message.setSubject(mailRequest.getSubject());
        message.setSubject("eapi");
        //邮件内容
        // message.setText(mailRequest.getText());
        String code = IdentifyingCode.getCode();
        message.setText("欢迎使用eapi，您的验证码为: " + code);
        //邮件发送时间
        message.setSentDate(new Date());

        // 验证是否已经给该邮箱发送验证码
        String sendTo = mailRequest.getSendTo();
        QueryWrapper<Identifycode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("emailaddress",sendTo);
        Identifycode record = identifycodeService.getOne(queryWrapper);
        if (record!=null){
            // 删除该记录
            identifycodeService.removeById(record);
        }
        // 新增发送记录
        Identifycode identifycode = new Identifycode();
        identifycode.setEmailAddress(sendTo);
        identifycode.setIdentifycode(code);
        identifycodeService.save(identifycode);

        // 发送邮件
        javaMailSender.send(message);
        log.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());
    }

    /*@Override
    public void sendHtmlMail(MailRequest mailRequest) {
        MimeMessage message = javaMailSender.createMimeMessage();
        checkMail(mailRequest);
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            //邮件发件人
            helper.setFrom(sendMailer);
            //邮件收件人 1或多个
            helper.setTo(mailRequest.getSendTo().split(","));
            //邮件主题
            helper.setSubject(mailRequest.getSubject());
            //邮件内容
            helper.setText(mailRequest.getText(),true);
            //邮件发送时间
            helper.setSentDate(new Date());

            String filePath = mailRequest.getFilePath();
            if (StringUtils.hasText(filePath)) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                helper.addAttachment(fileName, (DataSource) file);
            }
            javaMailSender.send(message);
            log.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常！",e);
        }
    }*/
}
